# encoding=utf-8_general_ci

import os.path
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

from update import update

import torndb

from config import *

class DesignHandler(tornado.web.RequestHandler):
    def get(self):
        if not self.get_secure_cookie('user'):
            self.redirect("/login")
            return
        
        username = self.get_secure_cookie("user")

        try:
            db = torndb.Connection(db_host, db_name, user = db_user, password= db_password)
        except:
            self.render("error.html", user = user_info, error_message = "Mysql Connection Error!", statu = "danger")
            return

        user_info = db.get("select * from user where username='"+username+"'")

        self.render("design.html", user = user_info)

    def post(self):
        if not self.get_secure_cookie('user'):
            self.redirect("/login")
            return
                
        username = self.get_secure_cookie("user")

        try:
            db = torndb.Connection(db_host, db_name, user = db_user, password= db_password)
        except:
            self.render("error.html", user = user_info, error_message = "Mysql Connection Error!", statu = "danger")
            return

        user_info = db.get("select * from user where username='"+username+"'")

        title = self.get_argument("title", "")
        fromwhere = self.get_argument("fromwhere", "")
        description = self.get_argument("description", "")
        hint = self.get_argument("hint","")
        inputdata = self.get_argument("input", "")
        outputdata = self.get_argument("output", "")
        source = self.get_argument("source", "")
        difficulty = self.get_argument("difficulty", "")
        timelimit = self.get_argument("timelimit", "")
        memlimit = self.get_argument("memlimit", "")
        
        if title == "" or description == "" or inputdata == "" or outputdata == "" or source == "":
            self.render("error.html", user = user_info, error_message = "Incomplete Input", statu="danger")
            return

        source = source.replace("%","%%")
        source = source.replace("\\","\\\\")
        description = description.replace("\\", "\\\\")

        db.execute("insert into problems (author,fromwhere,title,description,input,output,source,hint,timelimit,memlimit,difficulty) values ('%s','%s','%s','%s','%s','%s','%s','%s',%s,%s,%s)" % (str(username),str(fromwhere),str(title),description,str(inputdata),str(outputdata),source,hint,str(timelimit),str(memlimit), str(difficulty)))
        self.render("error.html", user = user_info, error_message = "Submit success, wait to be verified!", statu = "info")
